package com.zdp.filesync.notify.service.impl;

import com.alibaba.nacos.api.config.ConfigType;
import com.zdp.filesync.config.client.FileSyncClient;
import com.zdp.filesync.config.client.FileSyncClientConfig;
import com.zdp.filesync.config.client.FileSyncClientInfo;
import com.zdp.filesync.config.server.FileSyncServer;
import com.zdp.filesync.nacos.service.NacosApi;
import com.zdp.filesync.notify.service.NotifyClientSyncService;
import com.zdp.filesync.utils.YamlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class NotifyClientSyncServiceImpl implements NotifyClientSyncService {

    @Autowired
    private FileSyncClient fileSyncClient;

    @Autowired
    private NacosApi nacosApi;

    @Autowired
    private FileSyncServer fileSyncServer;
    @Override
    public void notifyClient(String filePath,String commentName) {
        List<FileSyncClientInfo> infoList = fileSyncClient.getInfoList();
        if(CollectionUtils.isEmpty(infoList)){
            log.info("当前客户端信息列表为空，不进行文件同步通知");
            return ;
        }
        List<FileSyncClientInfo> fileSyncClientInfos = infoList.stream().filter(info -> StringUtils.equals(filePath, info.getMonitorPath()))
                        .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(fileSyncClientInfos)){
            log.info("未在客户端信息列表中找到匹配的路径，不进行文件同步通知。路径:{}",filePath);
            return ;
        }
        for(FileSyncClientInfo fileSyncClientInfo : fileSyncClientInfos){
            fileSyncClientInfo.setServerVersion(fileSyncClientInfo.getServerVersion() + 1);
            fileSyncClientInfo.setCommentName(commentName);
        }
        // 推送到Nacos中
        FileSyncClientConfig fileSyncClientConfig = new FileSyncClientConfig();
        fileSyncClientConfig.setFileSyncClient(fileSyncClient);
        String config = YamlUtil.toYaml(fileSyncClientConfig);
        nacosApi.pushConfig(fileSyncServer.getNamespaceId(),fileSyncServer.getDataId(),fileSyncServer.getGroup(),
                config, ConfigType.YAML.getType());
        log.info("推送文件:{}的通知完毕",filePath);
    }
}
